
var common = require('./common.js');

var agents = {};
var agents_map = {};
var global_index = 0;

function add(addr) {
    if (!agents_map.hasOwnProperty(addr)) {
        agents_map[addr] = global_index++;
    }
    agents[addr] = addr;
    return agents_map[addr];
}

function del(addr) {
    agents[addr] = null;
}

function getIndex(addr) {
    if (agents_map.hasOwnProperty(addr)) {
        return agents_map[addr];
    } else {
        return -1;
    }
}

function list() {
    var out = [];
    for (var i in agents) {
        var agent = agents[i];
        if (agent == null) continue;
        out[i] = agents_map[i];
    }
    return out;
}

var tasks = new Array();

function ping() {
    if (tasks.length <= 0)
        return;

    var url = 'http://' + tasks[0] + '/api.ping?' + getIndex(tasks[0]);
    common.getUrlData(
        url,
        function (res) {
            tasks.splice(0, 1);
            ping();
        },
        function (err) {
            console.log('remove dead agent ' + tasks[0]);
            del(tasks[0]);
            tasks.splice(0, 1);
            ping();
        }
    );
}

function tick() {
    if (tasks.length > 0) return;

    for (var i in agents) {
        if (agents[i] == null) continue;
        tasks.push(i);
    }

    ping();
}

module.exports.add = add;
module.exports.del = del;
module.exports.getIndex = getIndex;
module.exports.list = list;
module.exports.tick = tick;
